
import moment from 'moment';


export function date(value, format = 'YYYY-MM-DD') {
  return mom(value).format(format);
}
// 日记格式的转化
export function dateFormat(value, format = 'YYYY-MM-DD', to = 'DD-MM-YYYY') {
  if (!value) return '';
  return mom(value, format).format(to);
}
// 获取moment 对象
export function mom(value, format) {
  if (!value && !format) return moment();
  if (value && format) return moment(value, format);
  if (value) return moment(value);
  return moment();
}
// 時間比較最大值
export function maxMom(a, b) {
  return moment.max(a, b)
}
// 時間比較最小值
export function minMom(a, b) {
  return moment.min(a, b)
}
// 计算年龄
export function getAge(birth, date, format = 'YYYY-MM-DD') {
  const d = mom(date, format)
  const b = mom(birth, format)
  const age = d.diff(b, 'years', true);
  return age
}
// 运行环境是否是微信
export function isWeixin() {
  let ua = navigator.userAgent.toLowerCase();
  return ua.indexOf('micromessenger') !== -1;
}

// 转千分位显示
export function thousandth(value, params) {
  const { negative, enableNull, placeholder, nonDec } = params || {};
  if (!value) return enableNull ? '' : (placeholder || '0.00');
  if (parseFloat(value) === 0) return (placeholder || '0.00');
  if (!negative || parseFloat(value) > 0) return `${!nonDec ? parseFloat(value).toFixed(2) : parseFloat(value)}`.replace(/\B(?=(\d{3})+\b)/g, ',');
  if (parseFloat(value) < 0) {
    return '(' + `${Math.abs(value)}`.replace(/\B(?=(\d{3})+\b)/g, ',') + ')';
  }
}
// 转千分位显示
export function thousandthInt(value , negative = false) {
  if (!value) return '--';
  if (parseFloat(value) === 0) return '0';
  if (!negative || parseFloat(value) > 0) return `${parseFloat(value)}`.replace(/\B(?=(\d{3})+\b)/g , ',');
  if (parseFloat(value) < 0) {
    return '(' + `${Math.abs(value)}`.replace(/\B(?=(\d{3})+\b)/g , ',') + ')';
  }
}

// js 对象转query 参数
export function objectToQuery() {
  console.log({ arguments: arguments })
  let obj = arguments[0];
  let prefix = arguments[1];
  if (typeof obj !== 'object') return '';
  const attrs = Object.keys(obj);
  return attrs.reduce((query, attr, index) => {
    if (index === 0 && !prefix) query += '?';
    if (typeof obj[attr] === 'object') {
      const subPrefix = prefix ? `${prefix}[${attr}]` : attr;
      query += this.objectToQuery(obj[attr], subPrefix);
    } else {
      if (prefix) {
        query += `${prefix}[${attr}]=${obj[attr]}`;
      } else {
        query += `${attr}=${obj[attr]}`;
      }
    }
    if (index !== attrs.length - 1) query += '&';
    return query;
  }, '');
}


// 上传文件类型判断
export function ifRightExt(event) {
  if (!event || !event.file) return false;
  if (['png', 'jpg', 'jpeg', 'pdf', 'heif', 'heic', 'bmp', 'docx', 'doc', 'xls', 'xlsx'].indexOf(event.file.name.split('.').pop().toLowerCase()) > -1) return true;
  return false;
}

export function isImg(extend) {
  if (!extend) return false
  return ['jpg', 'jpeg', 'png', 'bmp', 'heic', 'heif'].includes(extend.toLowerCase())
}

// 下载功能
export function downloadByTagA(url, name = 'file') {
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.setAttribute('download', name);
  document.body.appendChild(a);
  a.click();
}

// 获取后缀名
export function getExt(url) {
  if (!url) return '';
  const strs = url.split('.');
  return strs.length > 0 ? strs[strs.length -1] : '';
}

// 支付页面 不同系统的callback
export function openUrl(url) {
  const u = navigator.userAgent.toLowerCase()
  if (u.indexOf('iphone') > -1 || u.indexOf('ios') > -1 || (u.indexOf('safari') > -1 && u.indexOf('chrome') < 0)) {
    window.document.location.href = url
  } else {
    window.open(url, '_self')
  }
}

let timeout = null;
export function debounce(fn, wait = 1000) {
  if (timeout !== null) clearTimeout(timeout)
  timeout = setTimeout(fn, wait)
}
export function isPhone() {
  // 判断是否移动端
  const mobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
  return mobile != null
}
// 下载 blob 文件
export function downloadBlob(blob, options) {
  try {
    const { name } = options
    const link = document.createElement('a')
    const objecyUrl = URL.createObjectURL(blob)
    link.href = objecyUrl
    link.download = name
    link.click()
    URL.revokeObjectURL(objecyUrl)
    if (document.contains(link)) {
      document.removeChild(link)
    }
  } catch (error) {
    console.log('downloadBase64', error)
  }
}
